All files / web/src/app/api/households/[id]/members/[userId] route.ts

0% Statements 0/49
0% Branches 0/1
0% Functions 0/1
0% Lines 0/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                                                                                                   
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { getHouseholdDetail, isHouseholdMember, removeHouseholdMember } from '@/lib/household'

/**
 * DELETE /api/households/[id]/members/[userId]
 *
 * Remove a member from a household.
 * - Owner can remove any member (except themselves — must transfer ownership first)
 * - Members can only remove themselves (leave)
 */
export const DELETE = withAuth(
  async (_request, { userId: actingUserId, params }) => {
    const { id: householdId, userId: targetUserId } = (await params) as {
      id: string
      userId: string
    }

    // Verify the acting user is a member of the household
    const isMember = await isHouseholdMember(householdId, actingUserId)
    if (!isMember) {
      return NextResponse.json({ error: 'Not a member of this household' }, { status: 403 })
    }

    // Check permissions: owner can remove anyone, members can only leave
    const household = await getHouseholdDetail(householdId)
    if (!household) {
      return NextResponse.json({ error: 'Household not found' }, { status: 404 })
    }

    const isOwner = household.ownerId === actingUserId
    const isSelfLeave = actingUserId === targetUserId

    if (!isOwner && !isSelfLeave) {
      return NextResponse.json(
        { error: 'Only the owner can remove other members' },
        { status: 403 }
      )
    }

    const result = await removeHouseholdMember(householdId, targetUserId)
    if (!result.success) {
      return NextResponse.json({ error: result.error }, { status: 400 })
    }

    return NextResponse.json({ success: true })
  },
  { role: 'user' }
)